package com.ux.iot.jetlinks.util;

import cn.hutool.core.util.ObjectUtil;
import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;

public class NetUtilsTool {

  static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  private static final MediaType CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded");

 static OkHttpClient client = new OkHttpClient();

 public static  String unHeaderPost(String url, String jso) throws IOException{
     return  post(url,jso,null);
 }


 public static    String post(String url, String json,HashMap<String,String> headers) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request ;
        if(ObjectUtil.isEmpty(headers)){
            request=new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
        }else {
            request=new Request.Builder()
                    .url(url).headers(Headers.of(headers))
                    .post(body)
                    .build();
        }
        //同步
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            String value=response.body().string();
            System.out.println(value);
            return value;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    public static    String get(String url) throws IOException {

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        //同步
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            String value=response.body().string();
            System.out.println(value);
            return value;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }



    public static    String get(String url, HashMap<String,String> headers) throws IOException {

        Request request = new Request.Builder()
                .headers(Headers.of(headers))
                .url(url)
                .get()
                .build();
        //同步
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            String value=response.body().string();
            System.out.println(value);
            return value;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }




}
